const dayjs = require("dayjs");
const pinyin = require("pinyin").default || require("pinyin");
const { v4: uuidv4 } = require('uuid');

const jwt = require("jsonwebtoken");
const {JWT_SECRET} = require("../config/index"); // 改成你的

// 1.时间处理相关
// 格式化时间，自定义格式(dayjs)
exports.formatDate = (date, fmt) => {
  return dayjs(date).format(fmt);
};
// 获取时间: 2025-06-17 10:20:30
exports.getTime = () => {
  return dayjs().format("YYYY-MM-DD HH:mm:ss");
};
// 获取日期：2025-06-17
exports.getDate = () => {
  return dayjs().format("YYYY-MM-DD");
};

exports.getFileName = () => {
  return dayjs().format("YYYYMMDDHHmm")+uuidv4();
};

// 时间戳
exports.getTimeStamp = () => {
  return dayjs().unix();
};

// 2.格式化货币
exports.formatMoney = (num, point = 2) => {
  return num.toFixed(point);
};

// 3.文件上传相关
exports.uploadFile = (file) => {};

// 4.文件下载相关
exports.downloadFile = (file) => {};

// 5.拼音及编码相关
/**
 * 获取中文名称的拼音首字母缩写，并转为大写。
 * 例如："新鲜蔬菜" -> "XXSC"
 * @param {string} chineseName
 * @returns {string} 拼音首字母缩写
 */
exports.getChineseAcronym = (chineseName) => {
  if (!chineseName) return "";

  // 使用 pinyin 库获取每个字的拼音首字母
  const pinyins = pinyin(chineseName, {
    style: pinyin.STYLE_FIRST_LETTER, // 设置为只返回首字母
    heteronym: false, // 不处理多音字，简化逻辑
  });

  // 拼接所有首字母，并转为大写
  return pinyins.map((p) => p[0].toUpperCase()).join("");
};

// 6.获取客户端ip
/*
* @description: 获取客户端ip
* @param {*} req 请求对象
* @return {*} 客户端ip
* */
exports.getExtractIp =(req) =>{
  return (
      req.headers['x-forwarded-for'] ||
      req.ip ||
      req.connection.remoteAddress ||
      ''
  ).replace('::ffff:', '');
}

// 7.获取客户端类型
/*
* @description: 获取客户端类型
* @param {*} req 请求对象
* @return {*} 客户端类型
* */
exports.getClientType = (req) =>{
  const ua = (req.headers['user-agent'] || '').toLowerCase();

  if (!ua) return 'OTHER';

  if (ua.includes('iphone') || ua.includes('ipad') || ua.includes('ios')) {
    return 'IOS';
  }

  if (ua.includes('android')) {
    return 'ANDROID';
  }

  // 正常浏览器认为是 WEB
  if (
      ua.includes('chrome') ||
      ua.includes('safari') ||
      ua.includes('firefox') ||
      ua.includes('edge') ||
      ua.includes('windows') ||
      ua.includes('macintosh')
  ) {
    return 'WEB';
  }

  return 'OTHER';
}

// 8.从 Token 中获取用户 ID
/*
* @description: 从 Token 中获取用户 ID
* @param {*} req 请求对象
* @return {*} 用户 ID
* */
exports.getUserIdFromToken =(req) =>{
  try {
    const token = req.headers.authorization?.split(" ")[1];
    if (!token) return null;

    const decoded = jwt.verify(token, JWT_SECRET);
    console.log("decoded:", decoded)
    return decoded.user_id || null;
  } catch (err) {
    return null;
  }
}